#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>
struct ThreadData
{
    int sock_fd;
    std::string serverip_;
    struct sockaddr_in server;
    
};
void Usage(std::string proc)
{
    std::cout<<"\n\rUsage:"<<proc<<" serverip serverport"<<std::endl;
}
void* send_message(void*args)
{
    ThreadData* td=static_cast<ThreadData*>(args);
    std::string line;
    while(true)
    {
        std::cout<<"Please enter@"<<std::endl;
        std::getline(std::cin,line);
        sendto(td->sock_fd,line.c_str(),line.size(),0,(sockaddr*)&td->server,sizeof(td->server));
    }
    return nullptr;
}
void* recv_message(void*args)
{
    ThreadData* td=static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t templen=sizeof(temp);
       ssize_t n=recvfrom(td->sock_fd,buffer,sizeof(buffer)-1,0,(sockaddr*)&temp,&templen);
       if(n>0)
       {
        buffer[n]='\0';
        std::cerr<<buffer<<std::endl;
       }
    }
    return nullptr;
}
//udpclient srverip server port
int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }
    ThreadData td;
    td.serverip_=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    //1.创建套接字
   td.sock_fd= socket(AF_INET,SOCK_DGRAM,0);
   if(td.sock_fd<0)
   {
    return 2;
   }
   //2.准备数据
    memset(&td.server,0,sizeof(td.server));//初始化
    inet_pton(AF_INET,td.serverip_.c_str(),&td.server.sin_addr);//串转地址
    td.server.sin_family=AF_INET;
    td.server.sin_port=htons(serverport);//主机转网络字节序
    //3.需要绑定，OS自动绑定
    pthread_t send,recv;
    pthread_create(&send,nullptr,send_message,&td);
    pthread_create(&recv,nullptr,recv_message,&td);
    pthread_join(send,nullptr);
    pthread_join(recv,nullptr);

    return 0;
}